package com.lkl.demo.provider.config;

import com.lkl.demo.common.constant.RabbitMQConstant;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

@Configuration
public class TopicDelayConfig {

    // 路由交换机
    @Bean
    public DirectExchange directExchange() {
        return new DirectExchange(RabbitMQConstant.DELAY_DEAD_EXCHANGE, true, false);
    }

    // 延迟队列 延迟30s
    // 30s后，将死信消息发送给交换机
    @Bean
    public Queue delayQueue() {
        HashMap<String, Object> map = new HashMap<>();

        // x-dead-letter-exchange  当消息过期变成死信后重新发送到交换机
        map.put("x-dead-letter-exchange", RabbitMQConstant.DELAY_DEAD_EXCHANGE);
        // x-dead-letter-routing-key  当死信到达交换机，根据路由值发送到指定的死信队列
        map.put("x-dead-letter-routing-key", RabbitMQConstant.ROUTER_KEY_DEAD);
        // x-message-ttl 队列中消息过期时间 30s
        map.put("x-message-ttl", 30000);

        return new Queue(RabbitMQConstant.DELAY_QUEUE, true, false, false, map);
    }

    // 死信队列
    @Bean
    public Queue deadQueue() {
        return new Queue(RabbitMQConstant.DEAD_QUEUE, true);
    }

    // 队列交换机绑定关系
    @Bean
    public Binding binding1() {
        return BindingBuilder.bind(delayQueue()).to(directExchange()).with(RabbitMQConstant.ROUTER_KEY_DELAY);
    }

    @Bean
    public Binding binding2() {
        return BindingBuilder.bind(deadQueue()).to(directExchange()).with(RabbitMQConstant.ROUTER_KEY_DEAD);
    }
}
